//
//  ViewController.swift
//  Tech_Study
//
//  Created by onemade on 4/18/16.
//  Copyright © 2016 CNPC. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var newsTitle: UILabel!
    @IBOutlet weak var pubTime: UILabel!
    private var contentWebView: UIWebView!
    private var previousPoint: CGPoint?
    
    private var timer: NSTimer? = nil
    private var step: Int64?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        setupWebView()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func setupWebView(){
        contentWebView = UIWebView(frame: CGRectMake(0, self.pubTime.frame.origin.y + 10 , mainScrollView.frame.width, 500))
        contentWebView.scrollView.showsHorizontalScrollIndicator = false
        contentWebView.scrollView.showsVerticalScrollIndicator = false
        contentWebView.userInteractionEnabled = true
        contentWebView.delegate = self
        mainScrollView.delaysContentTouches = true
        contentWebView.autoresizesSubviews = true
        contentWebView.autoresizingMask = .FlexibleHeight
        self.mainScrollView.delegate = self
        self.mainScrollView.addSubview(contentWebView)
       let mainFileUrl =  NSBundle.mainBundle().pathForResource("main", ofType: "html")
        let data = NSData(contentsOfFile: mainFileUrl!)
       contentWebView.loadData(data!, MIMEType: "text/html", textEncodingName: "UTF-8", baseURL: NSURL())
    }
}

extension ViewController: UIGestureRecognizerDelegate{
    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

extension ViewController: UIScrollViewDelegate{
    
}

extension ViewController: UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        let height = webView.scrollView.contentSize.height > mainScrollView.frame.height ? webView.scrollView.contentSize.height : mainScrollView.frame.height
        
        contentWebView.frame = CGRectMake(0, self.pubTime.frame.origin.y + 20, mainScrollView.frame.width,  height)
        mainScrollView.addSubview(self.newsTitle)
        mainScrollView.addSubview(self.pubTime)
        mainScrollView.addSubview(contentWebView)
        contentWebView.scrollView.scrollEnabled = false
        self.mainScrollView.contentSize = CGSizeMake(mainScrollView.frame.width, contentWebView.frame.height+50)
        contentWebView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitUserSelect='none';")
        contentWebView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitTouchCallout='none';")
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPressDidFire(_:)))
        longPress.minimumPressDuration = 1
        longPress.allowableMovement = 20
        longPress.delegate = self
        mainScrollView.addGestureRecognizer(longPress)
    }
    func longPressDidFire(gestureRecognizer: UILongPressGestureRecognizer){
        let view = gestureRecognizer.view as! UIScrollView
        let point = gestureRecognizer.locationInView(view.superview)

        var centerBtn:UIButton?
        
        if mainScrollView.tracking {
            
        }

        if gestureRecognizer.state == .Began {
            mainScrollView.scrollEnabled = false
            centerBtn = generatorButton("", center: point)
            self.view.addSubview(centerBtn!)
            previousPoint = point
        }
        
        if  gestureRecognizer.state == .Changed {
            
            if point.x - previousPoint!.x > 50 {
                print("next")
            }
            if previousPoint!.x - point.x > 50 {
                print("previous")
            }
            if point.y - previousPoint!.y > 50 {
                 step = Int64((point.y - previousPoint!.y) / 10)
                
                timer?.invalidate()
                timer = NSTimer.scheduledTimerWithTimeInterval(0.05,target: self, selector: #selector(ViewController.scrollContentByPressing(_:)), userInfo: ["scrollView":view, "speed": -1.0], repeats: true )
            }
            if previousPoint!.y - point.y > 50 {
                
                step = -Int64((previousPoint!.y - point.y) / 10)
                
                print("\(step)")
                print("\(previousPoint!.y - point.y)")
                timer?.invalidate()
                timer = NSTimer.scheduledTimerWithTimeInterval(0.05,target: self, selector: #selector(ViewController.scrollContentByPressing(_:)), userInfo: ["scrollView":view, "speed": 1.0], repeats: true )
            }
        }
        
        
        if gestureRecognizer.state == .Ended {
           
            timer?.invalidate()
            dispatch_async(dispatch_get_main_queue(), {
                for subView in self.view.subviews {
                    if subView.isKindOfClass(UIButton) {
                        subView.removeFromSuperview()
                    }
                }
                 self.mainScrollView.scrollEnabled = true
            });
        }
    }
    
    func generatorButton(title: String, center: CGPoint) -> UIButton {
        let button = UIButton(frame: CGRectMake(center.x-50,center.y-50,100,100))
        button.backgroundColor = UIColor.lightGrayColor()
        button.alpha = 0.7
        button.setTitle(title, forState: .Normal)
        button.center = center
        button.titleLabel?.font = UIFont.systemFontOfSize(48)
        button.layer.cornerRadius = button.frame.size.width/2
        return button
    }
    
    func scrollContentByPressing(timer:NSTimer) {
        print(mainScrollView.contentOffset.y)
        if(mainScrollView.contentOffset.y < 0){
            mainScrollView.setContentOffset(CGPointZero, animated: true)
        }else if(mainScrollView.contentOffset.y > mainScrollView.contentSize.height - mainScrollView.frame.size.height){
            mainScrollView.setContentOffset(CGPointMake(0, mainScrollView.contentSize.height - mainScrollView.frame.size.height), animated: true)
        }else{
            mainScrollView.contentOffset.y += CGFloat(step!)
        }
        
        
        
//        mainScrollView.setContentOffset(CGPointMake(0, mainScrollView.contentOffset.y+100), animated: true)
        
//        if mainScrollView.contentOffset.y >= 0 {
//            mainScrollView.contentOffset.y += timer.userInfo?["speed"] as! CGFloat
//        mainScrollView.setContentOffset(CGPointZero, animated: true)
//        mainScrollView.scrollRectToVisible(CGRectMake(0, 1024, mainScrollView.frame.size.width, mainScrollView.frame.size.height), animated: true)
//        }
    }
    
//    func changeNewsStatable(sender: UIButton) {
//        UIView.animateWithDuration(0.5, animations: {
//            
//            }, completion: { finished in
//                for subView in self.view.subviews {
//                    if subView.isKindOfClass(UIButton) {
//                        subView.removeFromSuperview()
//                    }
//                }
//        })
//    }
}
